//
//  HomeViewController.m
//  AffectionBee
//
//  Created by 李通 on 16/8/18.
//  Copyright © 2016年 chivalrous. All rights reserved.
//

#import "HomeViewController.h"
#import "ScannerViewController.h"
#import "SearchViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "HomeCollectionHeaderView.h"
#import "HomeHeaderFooterView.h"
#import "SupermarketViewController.h"
#import "IconsAndActivitiesModel.h"
#import "FirstCellModel.h"
#import "HotGoodsView.h"
#import "NewYearGiftsView.h"
#import "WarningView.h"
#import "DescViewController.h"
#import "RefreshGifHeader.h"


@interface HomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>


//声明一个4按钮数据数组
@property (nonatomic,strong) NSArray <IconsAndActivitiesModel *> *iconsArray;
//声明一个新年惠tableView数据数组
@property (nonatomic,strong) NSArray <IconsAndActivitiesModel *> *activitiesArray;
//声明一个新鲜热卖数据数组
@property (nonatomic,strong) NSArray <FirstCellModel *> *firstCellArray;
//图片轮播器的数据数组
@property (nonatomic,strong) NSArray <IconsAndActivitiesModel *> *adArray;

/*  UI控制支持属性  */
//购物车badge动画标识
@property (nonatomic,assign) NSInteger index;
//collectionView全局flowLayout属性
@property (nonatomic,strong) UICollectionViewFlowLayout *flowLayout;
//库存不足提醒
@property (nonatomic,strong) WarningView *warningView;
//商品添加到购物车动画layer
@property (nonatomic,strong) NSMutableArray <CALayer *> *animationLayers;
//标记是否正在动画
@property (nonatomic,assign) BOOL isAnimation;
//标记当前滑动位置
@property (nonatomic,assign) CGFloat lastContentOffsetY;

@end

static NSString *giftcell = @"giftCell";
static NSString *identifier = @"homeCell";
static NSString *headerIdentifier = @"homeHeader";
static NSString *headerViewIdentifier = @"headerView";
static NSString *footerViewIdentifier = @"footerView";

@implementation HomeViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.collectionView.backgroundColor = kHomeBGColor;
    
    [self setupNavBarItems];
    [self registerCollectionViewContentControl];
    //设置内边距
    self.flowLayout.sectionInset = UIEdgeInsetsMake(5, 10, 10, 10);
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noticeWithTitle:) name:@"notice" object:nil];
    //首次启动界面时进行网络请求
    [self startDisplayWithData];
}

- (void)refresh {
    
    __weak __typeof(self)weakSelf = self;
    self.collectionView.mj_header = [RefreshGifHeader headerWithRefreshingBlock:^{
       [weakSelf.collectionView.mj_header endRefreshingWithCompletionBlock:^{
           [weakSelf.collectionView reloadData];
       }];
    }];
    [self.collectionView.mj_header beginRefreshing];
}



//重写init方法调整collectionView布局
- (instancetype)init {
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    self.flowLayout = flowLayout;
    return [super initWithCollectionViewLayout:flowLayout];
}

//注册collectionView子控件
- (void)registerCollectionViewContentControl {
    
    [self.collectionView registerClass:[NewYearGiftsView class] forCellWithReuseIdentifier:giftcell];
    [self.collectionView registerClass:[HotGoodsView class] forCellWithReuseIdentifier:identifier];
    [self.collectionView registerClass:[HomeCollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier];
    [self.collectionView registerClass:[HomeHeaderFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewIdentifier];
    [self.collectionView registerClass:[HomeHeaderFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerViewIdentifier];
}

#pragma mark - titleItem
/*  首页左上角的扫码功能实现  */
- (void)setupNavBarItems {
    
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]init]barButtonWithTitle:@"扫一扫" titleColor:[UIColor blackColor] image:[[UIImage imageNamed:@"icon_black_scancode"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] hightLightImage:nil target:self action:@selector(didClickScanner) itemLoaction:YES];
    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]init]barButtonWithTitle:@"搜索" titleColor:[UIColor blackColor] image:[[UIImage imageNamed:@"icon_search"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] hightLightImage:nil target:self action:@selector(didClickSearch) itemLoaction:NO];
}
//跳转到扫码界面
- (void)didClickScanner {
    
    [self.navigationController pushViewController:[[ScannerViewController alloc] init] animated:YES];
}
//跳转到搜索界面
- (void)didClickSearch {
    
    [self.navigationController pushViewController:[[SearchViewController alloc] init] animated:YES];
}

#pragma mark - notice and animation
- (void)noticeWithTitle:(NSNotification *)notice {
    
    if (!self.warningView) {
        self.warningView = [[WarningView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
    }
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(disappear)];
    [self.warningView addGestureRecognizer:tap];
    [self.view addSubview:_warningView];
    [self.warningView warningWithTitle:notice.userInfo[@"title"]];
    self.warningView.center = self.view.center;
    self.warningView.hidden = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.warningView removeFromSuperview];
    });
}

- (void)disappear {
    
    self.warningView.hidden = YES;
}


#pragma mark - CollectionView DataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (section == 0) {
        return self.activitiesArray.count;
    } else {
        
        return self.firstCellArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewCell *cell;
    
    if (indexPath.section == 0) {
        NewYearGiftsView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:giftcell forIndexPath:indexPath];
        cell.model = self.activitiesArray[indexPath.row];
        return cell;
    }
    
    if (indexPath.section == 1) {
        HotGoodsView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
        cell.model = self.firstCellArray[indexPath.row];
        cell.animationBlock = ^(UIImageView *imageView){
            [self addProductsAnimation:imageView];
            if (self.badgeValueBlock) {
                _badgeValueBlock([NSString stringWithFormat:@"%ld",++self.index]);
            }
        };
        return cell;
    }
    return cell;
}

//商品添加到购物车的动画
- (void)addProductsAnimation:(UIImageView *)imageView {
    
    if (self.animationLayers == nil)
    {
        self.animationLayers = [[NSMutableArray alloc]init];
    }
    
    CGRect frame = [imageView convertRect:imageView.bounds toView:self.view];
    CALayer *transitionLayer = [[CALayer alloc]init];
    transitionLayer.frame = frame;
    transitionLayer.contents = imageView.layer.contents;
    [self.view.layer addSublayer:transitionLayer];
    [self.animationLayers addObject:transitionLayer];
    
    CGPoint p1 = transitionLayer.position;
    CGPoint p3 = CGPointMake(self.view.width - self.view.width / 4 - self.view.width / 8 - 6, self.view.layer.bounds.size.height - 40);
    
    CAKeyframeAnimation *positionAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, nil, p1.x, p1.y);
    CGPathAddCurveToPoint(path, nil, p1.x, p1.y - 30, p3.x, p1.y - 30, p3.x, p3.y);
    positionAnimation.path = path;
    
    CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnimation.fromValue = @1;
    opacityAnimation.toValue = @0.9;
    opacityAnimation.fillMode = kCAFillModeForwards;
    opacityAnimation.removedOnCompletion = YES;
    
    CABasicAnimation *transformAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
    transformAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];    transformAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DScale(CATransform3DIdentity, 0.2, 0.2, 1)];
    
    CAAnimationGroup *groupAnimation = [[CAAnimationGroup alloc]init];
    groupAnimation.animations = @[positionAnimation, transformAnimation, opacityAnimation];
    groupAnimation.duration = 0.8;
    groupAnimation.delegate = self;
    
    [transitionLayer addAnimation:groupAnimation forKey:@"cartParabola"];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    
    if (self.animationLayers.count > 0) {
        CALayer *transitionLayer = self.animationLayers[0];
        transitionLayer.hidden = YES;
        [transitionLayer removeFromSuperlayer];
        [self.animationLayers removeObjectAtIndex:0];
        [self.view.layer removeAnimationForKey:@"cartParabola"];
    }
}

#pragma mark - sectionHeader or sectionFooter
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *view = nil;
    
    if (kind == UICollectionElementKindSectionHeader) {
        
        if (indexPath.section == 0) {
            //如果是第一组的HeaderView 则使用HomeCollectionHeaderView类来实例化
            HomeCollectionHeaderView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier forIndexPath:indexPath];
            //数据传递
            reusableView.iconData = self.iconsArray;
            reusableView.adData = self.adArray;
            reusableView.descBlock = ^(IconsAndActivitiesModel *model){
                [self turnToDescControllerWithTitle:model.name urlString:model.customURL];
            };
            view = reusableView;
            
        } else if (indexPath.section == 1){
            //如果是第二组的HeaderView 则使用HomeHeaderFooterView来实例化
            HomeHeaderFooterView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewIdentifier forIndexPath:indexPath];
            view = [headerView creatViewWithType:YES];
        }
    } else if (kind == UICollectionElementKindSectionFooter && indexPath.section == 1) {
        //如果是第二组的FooterView 则使用HomeHeaderFooterView类来实例化
        HomeHeaderFooterView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerViewIdentifier forIndexPath:indexPath];
        view = [footerView creatViewWithType:NO];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(turnToMore)];
        [footerView addGestureRecognizer:tap];
    }
    return view;
}

//MYMARK: - 更多商品跳转
- (void)turnToMore {
    
    self.tabBarController.selectedIndex = 1;
}

//跳转到详情页面
- (void)turnToDescControllerWithTitle:(NSString *)title urlString:(NSString *)customURL {
    DescViewController *descController = [[DescViewController alloc]init];
    descController.customURL = customURL;
    descController.title = title;
    [self.navigationController pushViewController:descController animated:YES];
}

#pragma mark - CollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        IconsAndActivitiesModel *model = self.activitiesArray[indexPath.row];
        [self turnToDescControllerWithTitle:model.name urlString:model.customURL];
    }
}

//cell开始出现的时候调用
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0 && (indexPath.row == 0 || indexPath.row == 1)) {
        return;
    }
    if (self.isAnimation) {
        
        [self startAnimation:cell offsetY:80 duration:1.0];
    }
}

- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 1) {
        if (self.isAnimation) {
            
            [self startAnimation:view offsetY:60 duration:0.8];
        }
    }
}

//如果是从下往上滑，则停止动画
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    self.isAnimation = self.lastContentOffsetY < scrollView.contentOffset.y;
    self.lastContentOffsetY = scrollView.contentOffset.y;
    //如果正在滑动则停止商品添加到购物车动画
    if (self.animationLayers.count > 0) {
        CALayer *transitionLayer = self.animationLayers[0];
        transitionLayer.hidden = YES;
    }
}

//下拉刷新
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    
    if (scrollView.contentOffset.y < -100) {
        
        [self refresh];
    }
}

//滚动时Cell滑动显示的动画
- (void)startAnimation:(UIView *)view offsetY:(CGFloat)y duration:(NSTimeInterval)duration {
    
    view.transform = CGAffineTransformMakeTranslation(0, y);
    
    [UIView animateWithDuration:duration animations:^{
        view.transform = CGAffineTransformIdentity;
    }];
}

#pragma mark - CollectionViewDelegateFlowLayout
//为不同section的item设置不同的Size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGSize itemSize = CGSizeZero;
    
    if (indexPath.section == 0) {
        itemSize = CGSizeMake(kScreenSize.width - 20, 140);
    } else if (indexPath.section == 1) {
        itemSize = CGSizeMake((kScreenSize.width - 20) * 0.5 - 5, 250);
    }
    return itemSize;
}

//为不同section的headerView设置不同的Size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    CGSize referenceSize = CGSizeZero;
    
    if (section == 0) {
        referenceSize = CGSizeMake(kScreenSize.width, 200);
    } else if (section == 1) {
        referenceSize = CGSizeMake(kScreenSize.width, 20);
    }
    return referenceSize;
}

//为不同section的fotterView设置不同的Size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    
    CGSize referenceSize = CGSizeZero;
    
    if (section == 1) {
        referenceSize = CGSizeMake(kScreenSize.width, 50);
    }
    return referenceSize;
}


#pragma mark - load Data
- (void)startDisplayWithData {
    
    //(1)urlString
    NSString *urlString = @"http://iosapi.itcast.cn/loveBeen/firstSell.json.php";
    
    //(2)参数
    NSDictionary *param = @{@"call":@2};
    
    [FirstCellModel GetFirstCellDataArrayWithUrl:urlString andParameter:param Sucess:^(NSArray<FirstCellModel *> *dataArray) {
        
        _firstCellArray = dataArray;
        [self.collectionView reloadData];
    } Error:^{
        ABLog(@"网络数据获取失败");
    }];
    
    [IconsAndActivitiesModel GetIconDataArraySucess:^(NSDictionary *dataDict) {
        [dataDict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            if ([key isEqual: @"focus"]) {
                self.adArray = dataDict[@"focus"];
            }
            if ([key isEqual: @"icons"]) {
                self.iconsArray = dataDict[@"icons"];
            }
            if ([key isEqual: @"activities"]) {
                self.activitiesArray = dataDict[@"activities"];
            }
        }];
        [self.collectionView reloadData];
    } Error:^{
        ABLog(@"完了出错了");
    }];
}

#pragma mark - others
//移除通知
- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
